package leecode.array;

/**
 * @author wangxi created on 2024/8/2 23:26
 * @version v1.0
 *
 * https://leetcode.cn/problems/compare-version-numbers/
 */
public class CompareVersion {

    public static void main(String[] args) {
        CompareVersion version = new CompareVersion();
        int i = version.compareVersion("1.2", "1.10");
        System.out.println(i);
    }


    public int compareVersion(String version1, String version2) {
        if (version1 == null || version2 == null) {
            return 0;
        }
        // java 的split方法碰到这些：(    [     {    /    ^    -    $     ¦    }    ]    )    ?    *    +    .
        // 需要转义
        String[] nums1 = version1.split("\\.");
        String[] nums2 = version2.split("\\.");
        int i = 0;
        int j = 0;
        while (i < nums1.length || j < nums2.length) {
            int a = 0;
            int b = 0;
            if (i < nums1.length) {
                a = convert(nums1[i++]);
            }
            if (j < nums2.length) {
                b = convert(nums2[j++]);
            }
            if (a > b) {
                return 1;
            } else if (a < b) {
                return -1;
            }
        }
        return 0;
    }

    private int convert(String s) {
        // 去除前导0
        int i = 0;
        for (; i < s.length(); i++) {
            if (s.charAt(i) != '0') {
                break;
            }
        }
        if (i < s.length()) {
            return Integer.parseInt(s.substring(i, s.length()));
        } else {
            return 0;
        }
    }

}
